package com.tjp.eight.ui.fragment.sub;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.widget.PullRefreshLayout;
import com.google.gson.Gson;
import com.tjp.eight.R;
import com.tjp.eight.RxBus;
import com.tjp.eight.comment.AppManager;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.utils.ActivityUtils;
import com.tjp.eight.utils.BitmapUtils;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.DialogSendingComment;
import com.tjp.eight.views.LogoutDailog;
import com.tjp.eight.views.NoScrollViewPager;
import com.tjp.eight.views.rcview.EndlessRecyclerOnScrollListener;
import com.tjp.eight.views.rcview.HeaderViewRecyclerAdapter;

import org.hamcrest.core.Is;

import java.util.ArrayList;

import jp.wasabeef.recyclerview.animators.FadeInAnimator;
import jp.wasabeef.recyclerview.animators.SlideInDownAnimator;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/2/17.
 */

public class FragmentSub extends BaseFragment<SubPresenter> implements SubView {
    private ImageView iv_no_data;
    private ImageView iv_no_data2;

    private PullRefreshLayout prl_sub_my;
    private PullRefreshLayout prl_sub_my2;
    private View footView;
    private View footView2;
    private RecyclerView recyclerView;
    private HeaderViewRecyclerAdapter headerViewRecyclerAdapter;
    private SubAdapter subAdapter;
    private RecyclerView recyclerView2;
    private HeaderViewRecyclerAdapter headerViewRecyclerAdapter2;
    private SubAdapter subAdapter2;

    private NoScrollViewPager viewPager;

    private LinearLayout llMySub;
    private TextView tvMySub;
    private View vMySub;
    private LinearLayout llMoreSub;
    private TextView tvMoreSub;
    private View vMoreSub;

    private RelativeLayout rlNavBack;
    private ImageView ivNavBack;
    private TextView tvTitle;
    private EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener;
    private EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener2;
    private Observable<SubEvent> observable;
    private int myPage = 1;
    private int morePage = 1;
    private boolean isMyR = false;
    private boolean isMoreR = false;

    private SubItemModel.ItemModel currentSub;
    private SubItemModel.ItemModel currentSub2;

    int currentColor = Color.parseColor("#000000");
    int normalColor = Color.parseColor("#999999");

    private DialogSendingComment sendingDialog;
    private LogoutDailog dialogLogin;

    @Override
    protected SubPresenter createPresenter() {
        return new SubPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = inflater.from(getContext()).inflate(R.layout.fragment_sub, container, false);

        }
        initViews();
        regOb();
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter.loadMyData(getMyJson());
        presenter.loadMoreData(getMoreJson());
    }

    @Override
    public void loadMyData(SubItemModel model) {
        setNoLoad();
        if (model != null) {
            if (IsSuccessUtils.isSuccess(model.result)) {
                if (isMyR) {
                    subAdapter.cData(model.data);
                } else
                    subAdapter.addData(model.data);

                isMyR = false;
                if (subAdapter.getItemCount() >= model.total_items) {
                    footView.setVisibility(View.INVISIBLE);
                } else {
                    footView.setVisibility(View.VISIBLE);
                }
            } else {
                ToatUtils.toastCommentFail(getContext(), model.msg);
            }
        }
        if (subAdapter.getItemCount() == 0) {
            iv_no_data.setVisibility(View.VISIBLE);
            prl_sub_my.setVisibility(View.GONE);
            footView.setVisibility(View.INVISIBLE);
        } else {
            iv_no_data.setVisibility(View.GONE);
            prl_sub_my.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void loadMoreData(SubItemModel model) {
        setNoLoad();
        if (model != null) {
            if (IsSuccessUtils.isSuccess(model.result)) {
                if (isMoreR) {
                    subAdapter2.cData(model.data);
                } else
                    subAdapter2.addData(model.data);

                isMoreR = false;
                if (subAdapter2.getItemCount() >= model.total_items) {
                    footView2.setVisibility(View.INVISIBLE);
                } else {
                    footView2.setVisibility(View.VISIBLE);
                }
            } else {
                ToatUtils.toastCommentFail(getContext(), model.msg);
            }
        }
        if (subAdapter2.getItemCount() == 0) {
            iv_no_data2.setVisibility(View.VISIBLE);
            prl_sub_my2.setVisibility(View.GONE);
        } else {
            iv_no_data2.setVisibility(View.GONE);
            prl_sub_my2.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void loadFail(String msg) {
        setNoLoad();
        ToatUtils.toastCommentFail(getContext(), msg);
    }

    @Override
    public void subSuccess(SubResultModel model) {
        dismissLoading();
        if (model == null) return;
        if (IsSuccessUtils.isSuccess(model.result)) {
            ToatUtils.toastSuccess(getContext(), "取消订阅");
            currentSub.subscibe = model.subscibe;
            if (currentSub.subscibe < 0) {
                currentSub.subscibe = 0;
            }
            subAdapter.removeData(currentSub);
            subAdapter2.addData(currentSub);
        } else {
            ToatUtils.toastCommentFail(getContext(), model.msg);
        }
    }

    @Override
    public void subMoreSuccess(SubResultModel model) {
        dismissLoading();
        if (model == null) return;
        if (IsSuccessUtils.isSuccess(model.result)) {
            ToatUtils.toastSuccess(getContext(), "订阅成功");
            currentSub2.subscibe = model.subscibe;
            if (currentSub2.subscibe < 0) {
                currentSub2.subscibe = 0;
            }
            subAdapter.addData(currentSub2);
            subAdapter2.removeData(currentSub2);
            iv_no_data.setVisibility(View.GONE);
            prl_sub_my.setVisibility(View.VISIBLE);
            footView.setVisibility(View.INVISIBLE);
        } else {
            ToatUtils.toastCommentFail(getContext(), model.msg);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegOb();
    }

    private String getMyJson() {
        SubPostModel model = new SubPostModel();
        model.type = "yes";
        model.page = myPage;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private String getMoreJson() {
        SubPostModel model = new SubPostModel();
        model.type = "no";
        model.page = morePage;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private String getSubJson(SubItemModel.ItemModel model) {
        SubPModel pmodel = new SubPModel();
        pmodel.caid = model.caid;
        pmodel.uid = SharePreferencesUtils.getUid();
        pmodel.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(pmodel);
    }

    private void unRegOb() {
        if (observable != null) {
            RxBus.getInstance().unregister(SubEvent.class, observable);
        }
    }

    private void regOb() {
        observable = RxBus.getInstance().register(SubEvent.class);
        observable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<SubEvent>() {
            @Override
            public void call(SubEvent subEvent) {
                if (subEvent.if_subscibe == 1) {
                    subAdapter.addData(subEvent.model);
                    subAdapter2.removeData(subEvent.model);
                } else {
                    subAdapter2.addData(subEvent.model);
                    subAdapter.removeData(subEvent.model);
                }
            }
        });
    }

    private void setNoLoad() {
        prl_sub_my.setRefreshing(false);
        prl_sub_my2.setRefreshing(false);
    }

    void changeSubTitle(int type) {
        viewPager.setCurrentItem(type);
        if (type == 0) {
            tvMySub.setTextColor(currentColor);
            tvMoreSub.setTextColor(normalColor);
            vMySub.setVisibility(View.VISIBLE);
            vMoreSub.setVisibility(View.INVISIBLE);
        } else {
            tvMySub.setTextColor(normalColor);
            tvMoreSub.setTextColor(currentColor);
            vMySub.setVisibility(View.INVISIBLE);
            vMoreSub.setVisibility(View.VISIBLE);
        }
    }

    void initViews() {
        rlNavBack = (RelativeLayout) contentView.findViewById(R.id.rl_head_left);
        rlNavBack.setVisibility(View.VISIBLE);
        rlNavBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getAppManager().finishActivity(getActivity());
            }
        });
        ivNavBack = (ImageView) contentView.findViewById(R.id.iv_head_left);
        ivNavBack.setImageBitmap(BitmapUtils.getBitmap(getContext(), R.drawable.top_back));
        tvTitle = (TextView) contentView.findViewById(R.id.tv_title);
        tvTitle.setText("更多订阅");


        viewPager = (NoScrollViewPager) contentView.findViewById(R.id.vp_my_sub);
        viewPager.setNoScroll(true);
        final ArrayList<View> viewArrayList = new ArrayList<>();
        View viewMySub = LayoutInflater.from(getContext()).inflate(R.layout.frag_sub_viewpager, null, false);
        View viewMoreSub = LayoutInflater.from(getContext()).inflate(R.layout.frag_sub_viewpager, null, false);
        viewArrayList.add(viewMySub);
        viewArrayList.add(viewMoreSub);
        recyclerView = (RecyclerView) viewMySub.findViewById(R.id.rv_sub);
        recyclerView.setItemAnimator(new FadeInAnimator(new OvershootInterpolator(1f)));
        recyclerView.getItemAnimator().setAddDuration(1000);
        recyclerView2 = (RecyclerView) viewMoreSub.findViewById(R.id.rv_sub);
        recyclerView2.setItemAnimator(new FadeInAnimator(new OvershootInterpolator(1f)));
        recyclerView2.getItemAnimator().setAddDuration(1000);
        iv_no_data = (ImageView) viewMySub.findViewById(R.id.iv_no_data);
        iv_no_data2 = (ImageView) viewMoreSub.findViewById(R.id.iv_no_data);
        prl_sub_my = (PullRefreshLayout) viewMySub.findViewById(R.id.prl_sub_my);
        prl_sub_my2 = (PullRefreshLayout) viewMoreSub.findViewById(R.id.prl_sub_my);
        prl_sub_my.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                endlessRecyclerOnScrollListener.reSet();
                isMyR = true;
                myPage = 1;
                presenter.loadMyData(getMyJson());
            }
        });
        prl_sub_my2.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                endlessRecyclerOnScrollListener2.reSet();
                isMoreR = true;
                morePage = 1;
                presenter.loadMoreData(getMoreJson());
            }
        });
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        final GridLayoutManager gridLayoutManager2 = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);

        footView = LayoutInflater.from(getActivity()).inflate(R.layout.swipe_refresh_footer, recyclerView, false);

        subAdapter = new SubAdapter(getContext());
        headerViewRecyclerAdapter = new HeaderViewRecyclerAdapter(subAdapter);

        headerViewRecyclerAdapter.addFooterView(footView);
        recyclerView.setAdapter(headerViewRecyclerAdapter);
        endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(gridLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                myPage = currentPage;
                presenter.loadMyData(getMyJson());
            }
        };
        recyclerView.addOnScrollListener(endlessRecyclerOnScrollListener);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return headerViewRecyclerAdapter.isFootView(position) ? gridLayoutManager.getSpanCount() : 1;
            }
        });
        recyclerView2.setLayoutManager(gridLayoutManager2);
        footView2 = LayoutInflater.from(getActivity()).inflate(R.layout.swipe_refresh_footer, recyclerView2, false);
        subAdapter2 = new SubAdapter(getContext());
        subAdapter2.setType(2);
        headerViewRecyclerAdapter2 = new HeaderViewRecyclerAdapter(subAdapter2);
        headerViewRecyclerAdapter2.addFooterView(footView2);
        recyclerView2.setAdapter(headerViewRecyclerAdapter2);
        endlessRecyclerOnScrollListener2 = new EndlessRecyclerOnScrollListener(gridLayoutManager2) {
            @Override
            public void onLoadMore(int currentPage) {
                morePage = currentPage;
                presenter.loadMoreData(getMoreJson());
            }
        };
        recyclerView2.addOnScrollListener(endlessRecyclerOnScrollListener2);
        gridLayoutManager2.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return headerViewRecyclerAdapter2.isFootView(position) ? gridLayoutManager.getSpanCount() : 1;
            }
        });

        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return viewArrayList.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewArrayList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewArrayList.get(position));
                return viewArrayList.get(position);
            }
        });
        llMySub = (LinearLayout) contentView.findViewById(R.id.ll_my_sub);
        tvMySub = (TextView) contentView.findViewById(R.id.tv_my_sub);
        vMySub = contentView.findViewById(R.id.v_my_sub);
        llMoreSub = (LinearLayout) contentView.findViewById(R.id.ll_more_sub);
        tvMoreSub = (TextView) contentView.findViewById(R.id.tv_more_sub);
        vMoreSub = contentView.findViewById(R.id.v_more_sub);

        changeSubTitle(1);
        llMySub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeSubTitle(0);
            }
        });
        llMoreSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeSubTitle(1);
            }
        });
        iv_no_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeSubTitle(1);
            }
        });

        subAdapter.setSubThisSub(new SubAdapter.SubThisSub() {
            @Override
            public void sub(SubItemModel.ItemModel model) {
                if (SharePreferencesUtils.isLogin()) {
                    showLoading();
                    currentSub = model;
                    presenter.sub(getSubJson(model));
                } else {
                    showIsLogin();
                }
            }
        });
        subAdapter2.setSubThisSub(new SubAdapter.SubThisSub() {
            @Override
            public void sub(SubItemModel.ItemModel model) {
                if (SharePreferencesUtils.isLogin()) {
                    showLoading();
                    currentSub2 = model;
                    presenter.subMore(getSubJson(model));
                } else {
                    showIsLogin();
                }
            }
        });
    }

    void showIsLogin() {
        if (dialogLogin == null) {
            dialogLogin = new LogoutDailog(getActivity());
        }
        dialogLogin.setTextTitle("亲！你还没登录呢");
        dialogLogin.setLogoutInterface(new LogoutDailog.LogoutInterface() {
            @Override
            public void logout() {
                ActivityUtils.startLoginForResult(getActivity());
                dialogLogin.dismiss();
            }
        });
        dialogLogin.setCancelText("再去逛逛");
        dialogLogin.setOkText("去登录");
        dialogLogin.show();
    }

    private void showLoading() {
        if (sendingDialog == null) {
            sendingDialog = new DialogSendingComment(getContext());
        }
        sendingDialog.show();
    }

    private void dismissLoading() {
        if (sendingDialog == null) {
            sendingDialog = new DialogSendingComment(getContext());
        }
        sendingDialog.dismiss();
    }
}
